package com.nmgydy.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;

public class MD5Util {
	
    public static String sign(Map<String,String> params,String key){
    	List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
    	StringBuffer sb = new StringBuffer();
    	for(String mapKey : keys){
    		sb.append(mapKey);
    		sb.append('=');
    		sb.append(params.get(mapKey));
    		sb.append('&');
    	}
    	//sb.deleteCharAt(sb.length()-1);
    	sb.append("key=");
    	sb.append(key);
    	return md5(sb.toString()).toUpperCase();
    }

    public static String md5(String text) {
        return DigestUtils.md5Hex(getContentBytes(text, "UTF-8"));
    }
    
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }
    
	public static void main(String[] args) {
		TreeMap<String,String> params = new TreeMap<String, String>();
		//服务类型：微信
		params.put("service", "pay.weixin.scancode");
		//商户号
		params.put("mch_id", "001075552110006");
		//订单号
		params.put("out_trade_no", "141903606228");
		//商品描述
		params.put("body", "测试支付");
		//总金额
		params.put("total_fee", "1");
		//终端IP
		params.put("mch_create_ip", "127.0.0.1");
		//通知地址
		params.put("notify_url", "http://227.0.0.1:9001/javak/sds?123&23=3");
		//随机字符串
		params.put("nonce_str", "1409196838");
		//签名
		System.out.println(MD5Util.sign(params,"e1cf0ddcf6b47b59c351565d8ad717af"));
	}

}